import os
from pydub import AudioSegment


def convert_wav(filepath, save_path, convert_to):
    sourcefile = AudioSegment.from_wav(filepath)
    filename = filepath.split('\\')[-1].split('.wav')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def convert_m4a(filepath, save_path, convert_to):
    sourcefile = AudioSegment.from_file(filepath)
    filename = filepath.split('\\')[-1].split('.m4a')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def convert_mp3(filepath, save_path, convert_to):
    sourcefile = AudioSegment.from_mp3(filepath)
    filename = filepath.split('\\')[-1].split('.mp3')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def convert_ogg(filepath, save_path, convert_to):
    sourcefile = AudioSegment.from_ogg(filepath)
    filename = filepath.split('\\')[-1].split('.ogg')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def convert_flac(filepath, save_path, convert_to):
    sourcefile = AudioSegment.from_file(filepath)
    filename = filepath.split('\\')[-1].split('.flac')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def convert_any(filepath, save_path, source_from, convert_to):
    sourcefile = AudioSegment.from_file(filepath)
    filename = filepath.split('\\')[-1].split(f'.{source_from}')[0] + '.' + convert_to
    print(filename)
    sourcefile.export(save_path + filename, format=convert_to)


def get_file_name(filepath, file_suffix):
    file_list = []
    for root, dirs, files in os.walk(filepath):
        for file in files:
            if file_suffix in file.split('.')[-1]:
                file_list.append(os.path.join(root, file))
    return file_list


if __name__ == '__main__':
    source_path = 'C:\\Users\\HuaZai\\Workspace\\Code\\Tool\\music-converter\\data\\m4a'
    convert_path = 'C:\\Users\\HuaZai\\Workspace\\Code\\Tool\\music-converter\\data\\m4a\\convert\\'
    wav_list = get_file_name(source_path, 'm4a')
    for item in wav_list:
        convert_m4a(item, convert_path, 'mp3')
